<template>
  <div style="padding:10px">
     <main-layout>
      <div>
        <div class="back-view">
          <div class="title vxe-icon-feedback" >采购单添加
          </div>
          <div class="back" @click="onClose">
            <vxe-button  size="small" content="返回" icon="vxe-icon-undo"></vxe-button>
          </div>
        </div>

        <el-form ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px">
          <el-form-item label="收货信息" prop="userAddressId"> 
            <el-select v-model="formdata.userAddressId" 
                   style="width:400px;" 
                  @change="changeSelect"
                  clearable placeholder="请选择收货信息">
                  <el-option
                    v-for="item in addressList"
                    :key="item.userAddressId"
                    :label="item.receiverName"
                    :value="item.userAddressId">
                  </el-option>
                </el-select>
             <vxe-button icon="vxe-icon-add" size="mini" status="primary" style="margin-left:4px;" circle @click="addFlag=true"></vxe-button>
              <div style="width:100%;" v-if="formdata.userAddressId">
              <el-form  label-width="90px" class="show-box">
                <el-form-item label="收货人:">
                  {{addressInfo.receiverName}}
                </el-form-item>
                <el-form-item label="手机号码:">
                  {{addressInfo.receiverPhone}}
                </el-form-item>
                <el-form-item label="收货地址:">
                  {{addressInfo.receiverProvince}}/{{addressInfo.receiverCity}}/{{addressInfo.receiverRegion}}/{{addressInfo.receiverDetailAddress}}
                </el-form-item>
              </el-form>
            </div>
          </el-form-item>
          <el-form-item  label="选择商品"  :show-message="false" :required="true" style="margin-bottom:0;">
            <vxe-pulldown v-model="showPull">
              <template #default>  
                <el-input v-model="formdata.keyword"  clearable  style="width:60vw;" @input="changeQuery" @focus="focusEvent"  placeholder="搜索商品名称、规格、品牌" />
              </template>
              <template #dropdown>
                <div style="width:60vw;">
                   <gridTable tableHeight="300" 
                      v-if="queryList.length"
                      :data="queryList"
                      :showOverflow="false"
                      :columnsList="columnsList">
                        <template #cells="{row}">
                          <template v-if="row.pmsSpuImagesVoList && row.pmsSpuImagesVoList.length>0">
                                <imageView style="width:60px;height:60px"  :url="row.pmsSpuImagesVoList[0].url" />
                          </template>
                        </template>
                        <template #actions="{row}">
                            <vxe-button type="text" status="primary"  icon="vxe-icon-add" v-if="isAdd(row)" @click="confirmItem(row)">添加</vxe-button>
                            <vxe-button type="text" v-else  icon="vxe-icon-add">已添加</vxe-button>
                          </template>
                    </gridTable>
              </div>
            </template>
          </vxe-pulldown>
          </el-form-item>
          <el-form-item  prop="goodsList">
            <vxe-table
              border
              style="width:60vw;margin-top:10px"
              :row-config="{keyField: 'value', isHover: true}"
              :column-config="{resizable: true}"
              :scroll-y="{enabled: true}"
              :min-height="80"
              size="small"  
              :data="orderList">
              <vxe-column type="seq" width="60" title="序号"></vxe-column>
              <vxe-column field="label" title="商品图片" width="80">
                <template #default="{row}">
                      <template v-if="row.pmsSpuImagesVoList && row.pmsSpuImagesVoList.length>0">
                        <imageView style="width:60px;height:60px"  :url="row.pmsSpuImagesVoList[0].url" />
                      </template>
                 </template>
              </vxe-column>
              <vxe-column field="spuName" title="商品名称" width="180"></vxe-column>
              <vxe-column field="skuName" title="产品规格"></vxe-column>
              <vxe-column field="label" title="数量" align="center" width="180">
                <template #default="{row}">
                  <el-input-number v-model="row.buyQuantity" :min="1" :max="row.inventory"></el-input-number>
                 </template>
              </vxe-column>
              <vxe-column field="inventory" title="可售库存"></vxe-column>
              <vxe-column field="salesAmount.standardString" title="价格(元)"></vxe-column> 
              <vxe-column field="label" title="优惠(元)"></vxe-column>
              <vxe-column field="label" title="小计(元)"></vxe-column>
              <vxe-column field="label" title="操作">
                <template #default="{row,index}">
                    <vxe-button icon="vxe-icon-delete" @click="delItem(index)" title="删除" status="danger"></vxe-button>
                 </template>
              </vxe-column>
            </vxe-table> 
          </el-form-item>
          <el-form-item label="备注">
            <el-input
            type="textarea"
            style="width:400px;"
            :rows="6"
            placeholder="请输入备注"
            v-model="formdata.textarea">
          </el-input>
          </el-form-item> 
          <el-form-item label="">
            <el-checkbox v-model="formdata.checked">同意</el-checkbox> <span @click="openProcurement" style="color: #04AE70;cursor: pointer;">《采购服务协议》</span>
          </el-form-item>  
      </el-form>
        <div style="padding-left: 80px;padding-top:10px;padding-bottom:20px;">
          <el-button @click="onClose"><vxe-icon name="close"></vxe-icon> 取消</el-button>
          <el-button type="primary" @click="onSubmit"><vxe-icon name="check"></vxe-icon> 结算</el-button>
        </div>
        <addView v-if="addFlag" :show="addFlag" @success="getAddresInfo" @close="addFlag=false" />
        <procurementView v-if="procurementType" :show="procurementType" @close="procurementType=false" />
        </div>
    </main-layout>
</div> 
</template>
<script setup>
import { ref, onMounted, reactive,computed } from 'vue'
import {getSreachGoods,orderSettle,getAddressList} from '@/api/order'
import mainLayout from '@/components/custom/mainLayout.vue'
import imageView from '@/components/custom/image.vue'
import addView from '@/view/set/address/components/add.vue'
import procurementView from './components/procurement.vue'
import { VXETable } from 'vxe-table'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
const router = useRouter()
const ruleFormRef = ref(null)
const formdata = ref({})
const orderList = ref([])
const queryList = ref([])
const addressList = ref([])
const showPull = ref(false)
const addFlag = ref(false)
const saveType = ref(true)
const procurementType = ref(false)
const addressInfo =ref({})
const columnsList = ref([
      { title: '序号',type:'seq',align:'center'},
      {field: 'spuName', title: '商品名称',minWidth:'180',align:'left'},
      {field: 'skuNameImage',minWidth:'80', title: '商品图片',align:'center', slots: {default: 'cells'}},
      {field: 'skuName', title: '产品规格',minWidth:'120',align:'left'},
      {field: 'salesAmount.standardString', title: '价格(元)',minWidth:'80',align:'center'},
      {field: 'inventory', title: '可售库存',minWidth:'80',align:'center'},
      {field: 'brandName', title: '品牌',minWidth:'80',align:'center'},
      {title: '操作', width: 90,fixed:'right',field: 'orderSn',align:'center', slots: {default: 'actions'}}
   ])

const rules = computed(()=>{
  return {
      userAddressId: [
        { required: true, message: '请选择收货信息', trigger: 'change' }
      ],
      goodsList: [
        { required: !formdata.value.goodsList?.length, message: '未选择商品', trigger: 'blur' }
      ]
    }
})
onMounted(async () => {
  getAddresInfo()
})

const getAddresInfo =async ()=>{
  let res = await getAddressList({page:1,limit:100})
  if(res.success){
    addressList.value = res.data ||[]
  }
}

const changeQuery =async (val) => {
  if(!val){return}
  let res = await getSreachGoods({keyword:val,page:1,limit:10})
  if(res.success){
    queryList.value = res.data ||[]
  }
}

const changeSelect =(val)=>{
  addressInfo.value =  addressList.value.find((item)=>item.userAddressId==val)
}
const confirmItem = (row) => {
    orderList.value.push({...row,buyQuantity:1})
    formdata.value.goodsList =orderList.value
}

const isAdd = (row) => {
  let list =  orderList.value.filter((item)=>{return item.skuInfoId==row.skuInfoId})
  return list.length<=0
}

const focusEvent = () => {
  showPull.value = true
}

const delItem = (index) => {
  orderList.value.splice(index,1)
}

const onSubmit = async() => {
  await ruleFormRef.value.validate(async(valid, fields) => {
    if (valid && saveType.value) {
      if(!formdata.value.checked){
        VXETable.modal.message({ content:'请查看并同意采购服务协议' ,status:'warning'})
        return
      }
      saveType.value=false
     let res =await orderSettle({
          note:formdata.value.textarea,
          createName:userStore.userInfo.nickName,
          createId:userStore.userInfo.userId,
          createPhone:userStore.userInfo.farmList?.find((item)=>item.farmId==userStore.userInfo.farmId).contactsPhone||userStore.userInfo.userName,
          omsOrderItemAddDtoList:orderList.value.map((item)=>{
          return {
            buyQuantity:item.buyQuantity||1,
            spuInfoId:item.spuInfoId,
            skuInfoId:item.skuInfoId,
            supplierInfoId:item.supplierInfoId||1
          }
        }),
        receiverCity:addressInfo.value.receiverCity,
        receiverDetailAddress:addressInfo.value.receiverDetailAddress,
        receiverName:addressInfo.value.receiverName,
        receiverPhone:addressInfo.value.receiverPhone,
        receiverPostCode:addressInfo.value.receiverPostCode,
        receiverProvince:addressInfo.value.receiverProvince,
        receiverRegion:addressInfo.value.receiverRegion,
     })
      if (res.success) {
            localStorage.setItem('set-order-list',JSON.stringify(res.data))
            setTimeout(() => { saveType.value=true }, 500);
            router.push(`./create-order`)
      } else {
        saveType.value=true
        VXETable.modal.message({ content: res.message,status:'error'})
      }
    }
  })
}

const openProcurement = ()=>{
  procurementType.value = true
}
const onClose = ()=>{
  router.go(-1)
}
</script>
<style lang="scss" scoped>
.show-box{
    width:400px;
    background-color: #f5f5f5;
    margin: 10px 0;
    border-radius: 2px;
    padding: 10px 0;
}
.back-view{
    display: flex;
    justify-content: space-between;
    padding: 0 10px 15px 0;
    align-items: center;
    border-bottom:1px solid #ddd;
    margin-bottom:20px;
    .title{
      font-size:15px;
      font-weight: bold;
      color:#565656;
      position: relative;  


      text-indent:6px;
    }
    .title::before {
      content: "";
      display: block;
      width: 3px;
      background: #FF9C00;
      height: 16px;
      margin: 0 3px 0 0;
      position: absolute;
      top: 50%;
      margin-top: -9px;
  }
  .back{
    font-size:15px;
    color:#888;
    cursor: pointer;
  }
}
</style>
